//<editor-fold desc="Description">
package com.yaorange.api;

import com.yaorange.common.constant.CacheConstants;
import com.yaorange.common.constant.Constants;
import com.yaorange.common.core.domain.AjaxResult;
import com.yaorange.common.core.domain.entity.SysUser;
import com.yaorange.common.core.domain.model.LoginUser;
import com.yaorange.common.core.redis.RedisCache;
import com.yaorange.common.exception.ServiceException;
import com.yaorange.common.utils.SecurityUtils;
import com.yaorange.framework.web.service.SysLoginService;
import com.yaorange.framework.web.service.TokenService;
import com.yaorange.nongjt.domain.NjtLoginUser;
import com.yaorange.nongjt.domain.NjtUserPerfect;
import com.yaorange.nongjt.domain.NjtUserRegister;
import com.yaorange.nongjt.service.INjtUserPerfectService;
import com.yaorange.nongjt.service.INjtUserRegisterService;
import com.yaorange.nongjt.service.impl.NjtCommonService;
import com.yaorange.nongjt.vo.NjtUserLoginVo;
import com.yaorange.nongjt.vo.NjtUserRegisterVo;
import com.yaorange.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(value = "会员管理", tags = "会员管理")
@RestController
@RequestMapping("/api/user")
public class NjtUserAPI {

    @Autowired
    private INjtUserRegisterService userRegisterService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private NjtCommonService commonService;
    @Autowired
    private INjtUserPerfectService userPerfectService;
    @Autowired
    private TokenService tokenService;

    /**
     * 校验手机号是否可以被注册
     *
     * @param mobilePhone 注册手机号
     * @return
     */
    @ApiOperation("校验手机号是否可以被注册")
    @ApiImplicitParam(name = "mobilePhone", value = "注册手机号", required = true, dataType = "String")
    @GetMapping("/checkMobilePhone")
    public AjaxResult checkMobilePhone(@RequestParam("mobilePhone") String mobilePhone) {
        NjtUserRegister userRegister = userRegisterService.getByMobilePhone(mobilePhone);
        if (null != userRegister) {
            return AjaxResult.error("该手机号已被注册,请更换注册手机号");
        }
        return AjaxResult.success("手机号可用");
    }

//    /**
//     * 发送短信验证码
//     *
//     * @param mobilePhone 手机号
//     * @return
//     */
//    @ApiOperation("发送短信验证码")
//    @ApiImplicitParam(name = "mobilePhone", value = "手机号", required = true, dataType = "String")
//    @GetMapping("/sendValidateCode")
//    public AjaxResult sendValidateCode(@RequestParam("mobilePhone") String mobilePhone) {
//        // 生成6位随机验证码
//        String code = ValidateCodeUtils.generateValidateCode(6);
//        // 调用阿里云短信接口，给用户发送短信
//        JSONObject param = new JSONObject();
//        param.put("code", code);
//        Boolean result = SmsUtils.sendSms(mobilePhone, param, SmsEnum.REGISTER_TEMPLATE_CODE);
//        if (!result) {
//            log.info("短信发送接口，手机号，{}，验证码：{}，发送失败！", mobilePhone, code);
//            return AjaxResult.error("发送失败");
//        }
//        log.info("短信发送接口，手机号，{}，验证码：{}，发送成功！", mobilePhone, code);
//
//        // 将验证码放入Redis 设置失效时间为5分钟
//        redisCache.setCacheObject(CacheConstants.VALIDATE_PREFIX + mobilePhone
//                , code, 5, TimeUnit.MINUTES);
//        return AjaxResult.success("发送成功"
//                , code);
//    }

    /**
     * 生成固定验证码并存入Redis
     *
     * @param mobilePhone 手机号
     * @return 包含固定验证码的结果
     */
    @ApiOperation("生成固定验证码")
    @ApiImplicitParam(name = "mobilePhone", value = "手机号", required = true, dataType = "String")
    @GetMapping("/sendValidateCode")
    public AjaxResult sendValidateCode(@RequestParam("mobilePhone") String mobilePhone) {
        // 固定验证码为666666
        String code = "666666";

        // 将验证码放入Redis，设置5分钟过期
        redisCache.setCacheObject(CacheConstants.VALIDATE_PREFIX + mobilePhone,
                code, 5, TimeUnit.MINUTES);

        log.info("固定验证码生成成功，手机号：{}，验证码：{}", mobilePhone, code);

        return AjaxResult.success("验证码生成成功", code);
    }

    /**
     * 会员注册
     *
     * @param registerVO
     * @return
     */
    @ApiOperation("会员注册")
    @PostMapping("/register")
    public AjaxResult register(@Valid @RequestBody NjtUserRegisterVo registerVO) {
        String mobilePhone = registerVO.getMobilePhone();
        String password = registerVO.getPassword();
        String checkCode = registerVO.getCheckCode();
        // 比对验证码是否一致
        String code = redisCache.getCacheObject(CacheConstants.VALIDATE_PREFIX + mobilePhone);
        if (!checkCode.equals(code)) {
            return AjaxResult.error("验证码有误");
        }
        // 保存注册信息
        return userRegisterService.saveRegister(mobilePhone, password);
    }

    /**
     *会员登录
     *
     * @param loginVO 登录信息
     * @return 结果
     */
    @ApiOperation("会员登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody NjtUserLoginVo loginVO) {
        // 生成token
        String token = loginService.appLogin(loginVO.getUsername(), loginVO.getPassword());
        AjaxResult result = AjaxResult.success();
        result.put(Constants.TOKEN, token);
        return result;
    }

    /**
     * 获取当前登录用户信息
     *
     * @return
     */
    @ApiOperation("获取当前登录用户信息")
    @GetMapping("/queryLoginUser")
    public AjaxResult queryLoginUser() {
        NjtLoginUser loginUser = commonService.getLoginUser();
        return AjaxResult.success(loginUser);
    }

    /**
     * 刷新token
     *
     * @param request
     * @return
     */
    @ApiOperation(" 刷新token")
    @PostMapping("/refreshToken")
    public AjaxResult refreshToken(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        tokenService.refreshToken(loginUser);
        return AjaxResult.success("刷新成功");
    }

    /**
     * 完善信息
     *
     * @param
     * @return
     */
    @ApiOperation("完善信息")
    @PostMapping("/perfect")
    public AjaxResult perfect(@RequestBody NjtUserPerfect userPerfect) {
        return userPerfectService.perfectUser(userPerfect);
    }
}